﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using ConsolidationTool.WebParts.ControlTemplates;
using System.Web.UI.WebControls;
using ConsolidationTool.Common;
using ConsolidationTool.Common.Entities;
using System.Web.Script.Serialization;
using System.Data;
using System.Collections;
using System.Reflection;
using System.IO;
using Microsoft.SharePoint.Utilities;


namespace ConsolidationTool.WebParts
{
    public class FormStatus
    {
        public const string Published = "Published";
        public const string Locked = "Locked";
        public const string Draft = "Draft";
    }

    public class FormMode
    {
        public const string Display = "Display";
        public const string Edit = "Edit";
        public const string New = "New";
    }
    public class FSUserControlBase : UserControl
    {
        public FSReportBase FSReportPage
        {
            get
            {
                if (Page is FSReportBase)
                    return Page as FSReportBase;
                throw new Exception("this's not fsReport Page");
            }
        }
        public SPControlMode ControlMode { get; set; }

        public virtual SPListItem Item { get; set; }
        public Entity SelectedEntity { get; set; }
        public bool isBudgetMode
        {
            get
            {
                return Item.ParentList.Title.IndexOf("Budget") != -1;
            }
        }
        public CommonEntitySelector TopSelector { get; set; }
        public CommonButtomAction ButtomAction { get; set; }

        public bool ReportMode
        {
            get
            {
                return Request["m"] == "report";
            }
        }

        public virtual void Save()
        {
            if (ControlMode == SPControlMode.New)
            {
                var items = Item.ParentList.GetItems(new SPQuery()
                {
                    Query = string.Format(@" <Where>
                                <And>
                                    <Eq>
                                    <FieldRef Name='CoCd' />
                                    <Value Type='Text'>{0}</Value>
                                    </Eq>
                                    <And>
                                    <Eq>
                                        <FieldRef Name='Year' />
                                        <Value Type='Integer'>{1}</Value>
                                    </Eq>
                                    <Eq>
                                        <FieldRef Name='Month' />
                                        <Value Type='Integer'>{2}</Value>
                                    </Eq>
                                    </And>
                                </And>
                            </Where>", TopSelector.lbCoCd.Text, TopSelector.yearTextBox.Text, TopSelector.monthTextBox.Text)
                });
                if (items.Count > 0)
                {
                    //  Page.ClientScript.RegisterStartupScript(this.GetType(), "fs-notify-item-existed", string.Format("<script>alert('{0}-{1}-{2} it's already exist !');</script>", TopSelector.lbCoCd.Text, TopSelector.yearTextBox.Text, TopSelector.monthTextBox.Text));

                    return;
                }
            }
            Item["CoCd"] = TopSelector.lbCoCd.Text;
            Item["CoFullName"] = TopSelector.lbCompanyFullName.Text;
            Item["CoName"] = TopSelector.drpEntity.SelectedItem.Text;
            Item["Year"] = TopSelector.yearTextBox.Text;
            Item["Month"] = TopSelector.monthTextBox.Text;
            Item["Region"] = TopSelector.drpRegion.SelectedItem.Text;
            Item["SubRegion"] = TopSelector.drpSubRegion.SelectedItem != null ? TopSelector.drpSubRegion.SelectedItem.Text : "";
            Item["Currency"] = TopSelector.lbCompanyCurrency.Text;
            Item["Tonnage"] = TopSelector.lbCompanyTonnage.Text;
            Item["Control"] = TopSelector.ControlValue.Value;

            Item["Title"] = string.Format("{0}_{1}{2}",
                TopSelector.lbCoCd.Text.IsNullOrEmpty() ? TopSelector.drpRegion.SelectedItem.Text : TopSelector.lbCoCd.Text,
                TopSelector.yearTextBox.Text,
                TopSelector.monthTextBox.Text);

            SaveButton.SaveItem(SPContext.Current, false, string.Empty);

            SelectedEntity = BusinessService.getEntity(TopSelector.lbCoCd.Text);
            Guid MywebGuid = SPContext.Current.Web.ID;
            Guid MysiteGuid = SPContext.Current.Site.ID;

            Guid listID = Item.ParentList.ID;
            int listItemID = Item.ID;

            if (!Item.HasUniqueRoleAssignments && !TopSelector.lbCoCd.Text.IsNullOrEmpty())
                Utilities.UserRoleAssignment(MysiteGuid, MywebGuid, listID, listItemID, SelectedEntity, SPRoleType.WebDesigner);

            Utilities.CloseForm();
        }

        internal void bindCommonControl()
        {
            if (!ReportMode)
            {
                TopSelector.lbCoCd.Text = Item["CoCd"] + "";
                TopSelector.lbCompanyFullName.Text = Item["CoFullName"] + "";
                TopSelector.yearTextBox.Text = Item["Year"] + "";
                TopSelector.lbCompanyCurrency.Text = Item["Currency"] + "";
                TopSelector.lbCompanyTonnage.Text = Item["Tonnage"] + "";
                TopSelector.ControlValue.Value = Item["Control"] + "";

                TopSelector.monthTextBox.Text = Item["Month"] + "";
                TopSelector.drpRegion.Items.FindByText(Item["Region"] + "").Selected = true;
                TopSelector.drpRegion_SelectedIndexChanged(Item["Region"] + "", null);

                if ((Item["CoCd"] + "").IsNullOrEmpty()) return;
                TopSelector.drpSubRegion.Items.FindByText(Item["SubRegion"] + "").Selected = true;
                TopSelector.drpSubRegion_SelectedIndexChanged(Item["SubRegion"] + "", null);
                TopSelector.drpEntity.Items.FindByText(Item["CoName"] + "").Selected = true;
                TopSelector.drpEntity_SelectedIndexChanged(Item["CoName"] + "", null);
            }
        }

        internal void FormInitialization()
        {

            switch (ControlMode)
            {
                case SPControlMode.Display:

                    bindCommonControl();
                    // ViewState["BillData"] = Item["BillData"];
                    if (!ReportMode)
                    {
                        TopSelector.Controls.AllOfType<TextBox>().ToList().ForEach(p => p.Enabled = false);
                        TopSelector.Controls.AllOfType<DropDownList>().ToList().ForEach(p => p.Enabled = false);
                    }

                    ButtomAction.btSave.Visible = false;
                    TopSelector.RArea.Visible = false;

                    break;
                case SPControlMode.Edit:
                    
                    bindCommonControl();
                    TopSelector.RArea.Visible = false;
                    break;
                case SPControlMode.Invalid://已锁定 

                    break;
                case SPControlMode.New:

                    TopSelector.drpEntity.DataSource = TopSelector.entity_DataSource.Where(p => p.subRegionName == TopSelector.drpSubRegion.SelectedValue);

                    TopSelector.drpEntity.DataValueField = "CoCd"; TopSelector.drpEntity.DataTextField = "entityName";
                    TopSelector.drpEntity.DataBind();
                    TopSelector.drpEntity.Items.Insert(0, new ListItem("(None)", "0"));

                    break;
                default:
                    break;
            }
        }

        internal void OutputReport()
        {

            string billData = Item["BillData"] + "";
            if (billData == "") return;

            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            List<koOutputEntity> obj = Serializer.Deserialize<List<koOutputEntity>>(billData);

            obj = obj.Where(p => p.accountcode.ToLower() != "control").ToList();
            DataTable dt = obj.ToDataTable();

            var entity = new Entity()
            {
                CoCd = TopSelector.lbCoCd.Text,
                entityName = TopSelector.lbCompanyFullName.Text,
                Currency = TopSelector.lbCompanyCurrency.Text,
                Tonnage = TopSelector.lbCompanyTonnage.Text
            };
            string filename = Item.ParentList.Title;

            NPOIHelper.ExportDataTableToExcel(dt, filename, filename, "1", TopSelector.yearTextBox.Text, TopSelector.monthTextBox.Text, entity);

        }

        private bool IsNoFinancialApprovalPage()
        {

            return false;
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            //SPWeb web = SPContext.Current.Web;


            ////**************************************** 
            //// Get a reference the roles that are 
            //// bound to the current user and the role 
            //// definition to which we need to verify 
            //// the user against 
            //SPRoleDefinitionBindingCollection usersRoles = web.AllRolesForCurrentUser;
            //SPRoleDefinitionCollection roleDefinitions = web.RoleDefinitions;
            //SPRoleDefinition roleDefinition = roleDefinitions["Financial"];

            //bool noFinancialApproval = IsNoFinancialApprovalPage();
            //// Check if the user is in the role. If not 
            //// redirect the user to the access denied page 
            //if (usersRoles.Contains(roleDefinition) || noFinancialApproval)
            //{
            //    //******************************* 
            //    //Check if post back to run 
            //    //code that initiates the page 
            //    if (IsPostBack != true)
            //    {
            //        //Do your stuff here 
            //    }
            //}
            //else
            //{
            //    SPUtility.HandleAccessDenied(new Exception("The user have no promission to visit Financial information"));
            //}
        }

    }

}
